package com.example.joblinker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.joblinker.dto.JobDTO;
import com.example.joblinker.entity.Company;
import com.example.joblinker.entity.Job;
import com.example.joblinker.entity.User;
import com.example.joblinker.mapper.CompanyMapper;
import com.example.joblinker.mapper.JobMapper;
import com.example.joblinker.mapper.UserMapper;
import com.example.joblinker.service.JobService;
import com.example.joblinker.vo.JobVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JobServiceImpl implements JobService {

    @Resource
    private JobMapper jobMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private CompanyMapper companyMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JobVO createJob(JobDTO jobDTO, Long userId) {
        // 查询用户信息和关联的公司
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查用户是否为招聘者且已关联公司
        if (user.getRole() != 1) {
            throw new RuntimeException("只有招聘者可以发布职位");
        }
        
        if (user.getCompanyId() == null || user.getCompanyId() <= 0) {
            throw new RuntimeException("请先添加公司信息");
        }

        // 获取公司信息并设置冗余字段
        Company company = companyMapper.selectById(user.getCompanyId());
        if (company == null) {
            throw new RuntimeException("公司信息不存在");
        }

        // 创建职位
        Job job = new Job();
        BeanUtils.copyProperties(jobDTO, job);
        job.setCompanyId(user.getCompanyId());  // 使用用户关联的公司ID
        job.setUserId(userId);
        job.setStatus(0); // 默认为待审核状态
        job.setViewCount(0);
        job.setApplyCount(0);
        
        // 设置创建时间和更新时间
        job.setCreateTime(LocalDateTime.now());
        job.setUpdateTime(LocalDateTime.now());
        
        // 设置公司名称和Logo的冗余字段
        job.setCompanyName(company.getName());
        job.setCompanyLogo(company.getLogo());
        
        jobMapper.insert(job);

        return convertToVO(job);
    }

    @Override
    public JobVO getJobDetail(Long id) {
        Job job = jobMapper.selectById(id);
        if (job == null) {
            throw new RuntimeException("职位不存在");
        }

        // 更新浏览次数
        job.setViewCount(job.getViewCount() + 1);
        jobMapper.updateById(job);

        return convertToVO(job);
    }

    @Override
    public Page<JobVO> getJobList(Integer page, Integer size) {
        // 创建分页对象
        Page<Job> jobPage = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<Job> queryWrapper = new LambdaQueryWrapper<Job>()
                .eq(Job::getStatus, 1)  // 只查询状态为已发布的职位（状态1）
                .orderByDesc(Job::getCreateTime);

        // 执行查询
        jobMapper.selectPage(jobPage, queryWrapper);

        // 转换结果
        Page<JobVO> voPage = new Page<>();
        BeanUtils.copyProperties(jobPage, voPage, "records");
        voPage.setRecords(jobPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList()));

        return voPage;
    }

    @Override
    public Page<JobVO> searchJobs(String keyword, Long categoryId, String city, Integer status, Integer page, Integer size) {
        Page<Job> pageParams = new Page<>(page, size);
        
        // 构建查询条件
        LambdaQueryWrapper<Job> queryWrapper = new LambdaQueryWrapper<>();
        
        // 根据status参数过滤职位状态
        if (status != null) {
            queryWrapper.eq(Job::getStatus, status);
        } else {
            // 管理员界面不带status参数时查询所有状态的职位
            // 普通用户界面不带status参数时只查询已发布的职位
            queryWrapper.in(Job::getStatus, 0, 1, 2, 3);
        }
        
        // 关键词搜索（职位名称和职位描述）
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                .like(Job::getTitle, keyword)
                .or()
                .like(Job::getDescription, keyword)
                .or()
                .like(Job::getTags, keyword)  // 同时搜索标签
            );
        }
        
        // 分类ID筛选（职位类型）
        if (categoryId != null && categoryId > 0) {
            queryWrapper.eq(Job::getCategoryId, categoryId);
        }
        
        // 城市筛选
        if (StringUtils.hasText(city)) {
            queryWrapper.eq(Job::getCity, city);
        }
        
        // 默认按创建时间倒序排序（最新发布的在前面）
        queryWrapper.orderByDesc(Job::getCreateTime);
        
        // 执行分页查询
        Page<Job> jobPage = jobMapper.selectPage(pageParams, queryWrapper);
        
        // 转换为VO对象
        List<JobVO> voList = jobPage.getRecords().stream()
            .map(this::convertToVO)
            .collect(Collectors.toList());
        
        // 构建返回结果，使用实际记录数
        Page<JobVO> voPage = new Page<>(jobPage.getCurrent(), jobPage.getSize(), jobPage.getTotal());
        voPage.setRecords(voList);
        
        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JobVO updateJob(Long id, JobDTO jobDTO, Long userId) {
        // 查询职位信息
        Job job = jobMapper.selectById(id);
        if (job == null) {
            throw new RuntimeException("职位不存在");
        }
        
        // 检查权限
        if (!job.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作");
        }
        
        // 获取公司信息
        Company company = companyMapper.selectById(job.getCompanyId());
        if (company == null) {
            throw new RuntimeException("公司信息不存在");
        }
        
        // 更新职位信息
        BeanUtils.copyProperties(jobDTO, job);
        
        // 确保更新公司名称和Logo的冗余字段
        job.setCompanyName(company.getName());
        job.setCompanyLogo(company.getLogo());
        
        jobMapper.updateById(job);
        
        return convertToVO(job);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateJobStatus(Long id, Integer status, Long userId) {
        // 查询职位
        Job job = jobMapper.selectById(id);
        if (job == null) {
            throw new RuntimeException("职位不存在");
        }

        // 获取当前用户信息，检查是否为管理员
        User user = userMapper.selectById(userId);
        boolean isAdmin = user != null && user.getRole() == 2; // 角色2表示管理员
        
        // 校验权限：只有职位创建者或管理员可以修改
        if (!job.getUserId().equals(userId) && !isAdmin) {
            throw new RuntimeException("无权操作");
        }

        // 更新状态
        job.setStatus(status);
        jobMapper.updateById(job);
        
        // 记录操作日志
        System.out.println("职位状态已更新 - ID: " + id + ", 新状态: " + status + 
                           ", 操作用户: " + userId + (isAdmin ? " (管理员)" : ""));
    }

    @Override
    public Page<JobVO> getUserJobs(Long userId, Integer page, Integer size) {
        // 创建分页对象
        Page<Job> jobPage = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<Job> queryWrapper = new LambdaQueryWrapper<Job>()
                .eq(Job::getUserId, userId)
                .orderByDesc(Job::getCreateTime);

        // 执行查询
        jobMapper.selectPage(jobPage, queryWrapper);

        // 转换结果
        Page<JobVO> voPage = new Page<>();
        BeanUtils.copyProperties(jobPage, voPage, "records");
        voPage.setRecords(jobPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList()));

        return voPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncJobCompanyInfo() {
        // 查询所有职位信息
        List<Job> allJobs = jobMapper.selectList(null);
        
        for (Job job : allJobs) {
            // 对于每个职位，查询其关联的公司信息
            Company company = companyMapper.selectById(job.getCompanyId());
            
            // 如果公司存在，更新Job的冗余字段
            if (company != null) {
                // 只有当前字段为空或与公司信息不匹配时才更新
                boolean needUpdate = false;
                
                if (job.getCompanyName() == null || !job.getCompanyName().equals(company.getName())) {
                    job.setCompanyName(company.getName());
                    needUpdate = true;
                }
                
                if (job.getCompanyLogo() == null || !job.getCompanyLogo().equals(company.getLogo())) {
                    job.setCompanyLogo(company.getLogo());
                    needUpdate = true;
                }
                
                if (needUpdate) {
                    jobMapper.updateById(job);
                }
            }
        }
    }

    /**
     * 将实体转换为VO
     */
    private JobVO convertToVO(Job job) {
        JobVO vo = new JobVO();
        BeanUtils.copyProperties(job, vo);

        // 设置公司信息
        Company company = companyMapper.selectById(job.getCompanyId());
        if (company != null) {
            vo.setCompanyName(company.getName());
            vo.setCompanyLogo(company.getLogo());
        }

        return vo;
    }
} 